package com.example.smart.newsview;

import android.util.Log;
import android.util.Xml;
import android.widget.EditText;
import android.widget.ListView;

import com.example.smart.newsview.News;

import org.xmlpull.v1.XmlPullParser;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by smart on 2017/11/22.
 */

public class NewsInfo {
    public static List<News> find(String path) throws Exception{
        List<News> news=new ArrayList<>();
            URL url=new URL(path);
            News newsitem=null;
            HttpURLConnection conn= (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            int code=conn.getResponseCode();
            if (code==200){
                Log.e("TEST", "读取成功,开始解析...");
                InputStream is=conn.getInputStream();
                XmlPullParser parser=Xml.newPullParser();
                parser.setInput(is,"utf-8");
                int type=parser.getEventType();
                while (type!=XmlPullParser.END_DOCUMENT){
                    switch (type){
                        case XmlPullParser.START_TAG:
                            if ("item".equals(parser.getName())){
                                newsitem=new News();
                            }else if ("title".equals(parser.getName())){
                                newsitem.setTitle(parser.nextText());
                            }else if ("description".equals(parser.getName())){
                                newsitem.setDesciption(parser.nextText());
                            }
                            break;
                        case XmlPullParser.END_TAG:
                            if ("item".equals(parser.getName())) {
                                news.add(newsitem);
                            }
                            break;
                    }
                    type=parser.next();
                }
            }else {
                Log.e("TEST", "读取失败,请检查代码...");
                return null;
            }
        return news;
    }
}



